//
//  HXLCustomPageView.m
//  HXLScrollView
//
//  Created by 郝旭亮 on 13-7-8.
//  Copyright (c) 2013年 郝旭亮. All rights reserved.
//

#import "HXLCustomPageView.h"

@interface HXLCustomPageView (){
    NSInteger _pageCount;
    NSInteger _currentPageNumber;
    CGFloat _move_x;
    HXLCustomScrollView_SelectType _selectType;
    BOOL isTouchesBegin;
}
@property (nonatomic, retain) UIScrollView *pageScrollView;
@property (nonatomic, retain) UIPageControl *pageControl;
@property (nonatomic, retain) NSMutableArray *arrViews;
@property (nonatomic, retain) UITapGestureRecognizer *singleTap;


@end

@implementation HXLCustomPageView

@synthesize pageScrollView;
@synthesize pageControl;
@synthesize arrViews;
@synthesize pageViewDelegate;
@synthesize singleTap;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

-(void)dealloc
{
    [self removeGestureRecognizer:singleTap];
    [singleTap release];
    [pageScrollView release];
    [pageControl release];
    [arrViews release];
    [super dealloc];
}
/**
 //便利构造器
 
 @property frame       为本视图设置边界以及位置
 @property views       组成可翻页的每一页的view
 @property selectType  设置视图是否可以点击
 */
- (id)initPageViewWithFrame:(CGRect)frame
                      views:(NSArray *)views
                 selectType:(HXLCustomScrollView_SelectType)selectType{
    self = [super initWithFrame:frame];
    if (self) {
        _selectType = selectType;
        self.arrViews = [NSMutableArray arrayWithArray:views];
        _pageCount = views.count;
        _currentPageNumber = 0;
        _move_x = 0.0;
        self.userInteractionEnabled = YES;
        [self setMainView];
    }
    return self;
}

- (void)setMainView
{
    self.pageScrollView = [[[UIScrollView alloc] initWithFrame:self.bounds]autorelease];
    self.pageScrollView.pagingEnabled = YES;
    self.pageScrollView.showsHorizontalScrollIndicator = NO;
    self.pageScrollView.showsVerticalScrollIndicator = NO;
    if (_pageCount > 1) {
        [self.pageScrollView setContentSize:CGSizeMake(self.frame.size.width * 3, self.frame.size.height)];
        [self.pageScrollView setContentOffset:CGPointMake(self.frame.size.width, 0) animated:NO];
        _move_x = self.frame.size.width;
    }else{
        [self.pageScrollView setContentSize:CGSizeMake(self.frame.size.width, self.frame.size.height)];
    }
    
    if (_pageCount > 1)
    {
        self.pageScrollView.delegate = self;
    }
    else
    {
        self.pageScrollView.delegate = nil;
        if([self.arrViews count] > 0)
        {
            [self.pageScrollView addSubview:[self.arrViews objectAtIndex:0]];
        }
    }
    [self addSubview:self.pageScrollView];
    if (_pageCount > 1)
    {
        self.pageControl = [[[UIPageControl alloc] initWithFrame:CGRectMake(10, self.frame.size.height - 20, self.frame.size.width - 20, 20)]autorelease];
        [self.pageControl setNumberOfPages: _pageCount];
        [self.pageControl addTarget:self action:@selector(pageNumberChanged:) forControlEvents:UIControlEventValueChanged];
        [self.pageControl setCurrentPage:_currentPageNumber];
        self.pageControl.userInteractionEnabled = NO;
        [self addSubview:self.pageControl];
        [self reSetScrollViewOffSet];
    }
   
    
    self.singleTap = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTap:)]autorelease];
    self.singleTap.numberOfTapsRequired = 1;
    [self addGestureRecognizer:self.singleTap];
}



-(void)nextPage
{
    if(_pageCount <= 1)
    {
        return;
    }
    [UIScrollView animateWithDuration:1.0f animations:^{
        [self.pageScrollView setContentOffset: CGPointMake(self.frame.size.width * 2, 0.0f)];
    }];
  
    [self performSelector:@selector(scrollViewDidEndDecelerating:) withObject:self.pageScrollView afterDelay:1.2f];

}
-(void)prevPage
{
    if(_pageCount <= 1)
    {
        return;
    }
    [UIScrollView animateWithDuration:1.0f animations:^{
        [self.pageScrollView setContentOffset: CGPointMake(0.0f, 0.0f)];
    }];
    
    [self performSelector:@selector(scrollViewDidEndDecelerating:) withObject:self.pageScrollView afterDelay:1.2f];
}

- (void)reSetScrollViewOffSet{    
    for (UIView *view in self.pageScrollView.subviews) {
        [view removeFromSuperview];
    }
    
    CGFloat left = 0;
    BOOL needToCopyView = NO;
    for (NSInteger i = _currentPageNumber - 1 ; i < _currentPageNumber + 2; i++) {
        NSInteger index = i;
        needToCopyView = NO;
        if (index < 0) {
            index = _pageCount - 1;
            if(_pageCount == 2)
            {
                needToCopyView = YES;
            }
        }
        
        if (index == _pageCount) {
            index = 0;
            if(_pageCount == 2)
            {
                needToCopyView = YES;
            }
        }
        UIView *view = [self.arrViews objectAtIndex:index];
        UIView *copyView = nil;
        if(needToCopyView)
        {
            //当pageCount = 2的时候，由于实际只有两个视图实例，会导致左边滑动的时候出现空白，所以需要深度拷贝一个view，下面是深度拷贝view的方法，由于因为UIView没有实现NSCopying协议所以不能用[view copy]
            NSData *tempArchiveView = [NSKeyedArchiver archivedDataWithRootObject:view];
            copyView = [NSKeyedUnarchiver unarchiveObjectWithData:tempArchiveView];
        }
        else
        {
            copyView = view;
        }
        [copyView setFrame:CGRectMake(left, 0, self.frame.size.width, self.frame.size.height)];
        [self.pageScrollView addSubview:copyView];
        left += self.frame.size.width;
    }
    [self.pageScrollView setContentOffset:CGPointMake(self.frame.size.width, 0) animated:NO];
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    
    if ( scrollView.contentOffset.x != _move_x && (scrollView.contentOffset.x == self.frame.size.width*2 || scrollView.contentOffset.x == 0)) {
        NSLog(@"%s || current page before setted = %d",__FUNCTION__, _currentPageNumber);
        if (scrollView.contentOffset.x == 0) {
            _currentPageNumber--;
        }else{
            _currentPageNumber++;
        }
        NSLog(@"%s || total number of pages = %d", __FUNCTION__, _pageCount);
        if (_currentPageNumber == _pageCount) {
            _currentPageNumber = 0;
        }
        
        if (_currentPageNumber == -1) {
            _currentPageNumber = _pageCount -1;
        }
        
        [self.pageControl setCurrentPage:_currentPageNumber];
        NSLog(@"%s || current page after setted = %d",__FUNCTION__, _currentPageNumber);
        
        [self reSetScrollViewOffSet];
    }
}

- (void)pageNumberChanged:(UIPageControl *)pageCtl
{
    if (pageCtl.currentPage > _currentPageNumber) {
        [self.pageScrollView setContentOffset: CGPointMake(self.frame.size.width * 2, 0.0f) animated:YES];
        [self performSelector:@selector(scrollViewDidEndDecelerating:) withObject:self.pageScrollView afterDelay:0.5];
    }else if (pageCtl.currentPage < _currentPageNumber){
        [self.pageScrollView setContentOffset: CGPointMake(0.0f, 0.0f) animated:YES];
        [self performSelector:@selector(scrollViewDidEndDecelerating:) withObject:self.pageScrollView afterDelay:0.5];
    }

}


- (void)singleTap:(UITapGestureRecognizer *)tapGesture{
    if (_selectType != HXLCustomScrollView_SelectType_CanSelected) {
        return;
    }
    
    if (self.pageViewDelegate && [self.pageViewDelegate respondsToSelector:@selector(pageViewDidClickedWithPageNumber:)]) {
        [self.pageViewDelegate pageViewDidClickedWithPageNumber:_currentPageNumber];
    }
}

-(void)setPageControlTouchEnable:(BOOL)enable
{
    self.pageControl.userInteractionEnabled = enable;
}

#pragma mark- scrollView delegate
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    if (self.pageViewDelegate && [self.pageViewDelegate respondsToSelector:@selector(pageViewWillBeginDraging)]) {
        [self.pageViewDelegate pageViewWillBeginDraging];
    }
}

-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if (self.pageViewDelegate && [self.pageViewDelegate respondsToSelector:@selector(pageViewDidEndDraging)]) {
        [self.pageViewDelegate pageViewDidEndDraging];
    }
}

//add by wei.ye
-(void)replaceViewWithIndex:(int)index view:(UIView *)view
{
    if(view != nil)
    {
        [self.arrViews replaceObjectAtIndex:index withObject:view];
    }
}

-(void)setImageForImageViewByIndex:(int)index image:(UIImage *)img
{
    if([self.arrViews count] > index)
    {
        UIView *view = [self.arrViews objectAtIndex:index];
        if([view isKindOfClass:[UIImageView class]])
        {
            ((UIImageView *)view).image = img;
            NSLog(@"#######img width = %f",img.size.width);
            NSLog(@"#######imge frame = %f,%f,%f,%f",((UIImageView *)view).frame.origin.x,((UIImageView *)view).frame.origin.y,((UIImageView *)view).frame.size.width,((UIImageView *)view).frame.size.height);
        }
        
    }
}

-(int)getPageCount
{
    return [self.arrViews count];
}

-(void)setPageViews:(NSArray *)views
{
    _pageCount = [views count];
    self.arrViews = [NSMutableArray arrayWithArray:views];
    [self removeGestureRecognizer:self.singleTap];
    _currentPageNumber = 0;
    _move_x = 0.0;
    self.userInteractionEnabled = YES;
    [self setMainView];
}


@end
